// store/permission.js
import {
  asyncRouterMap,
  constantRoutes
} from '@/router';

function hasPermission(roles, route) {
  if (route.meta && route.meta.role) {
    return roles.some(role => route.meta.role.indexOf(role) >= 0)
    // return route.find(rol => rol.meta.role.indexOf(roles) >= 0)

  } else {
    return true
  }
}

export function filterAsyncRoutes(routes, roles) {
  const res = []

  routes.forEach(route => {
    const tmp = {
      ...route
    }
    if (hasPermission(roles, tmp)) {
      if (tmp.children) {
        tmp.children = filterAsyncRoutes(tmp.children, roles)
      }
      res.push(tmp)
    }
  })

  return res
}


const state = {
  routers: constantRoutes,
  addRouters: []
}
const mutations = {
  SET_ROUTES: (state, rout) => {
    state.addRouters = rout;
    state.routers = constantRoutes.concat(rout);
  }
}
const actions = {
  GenerateRoutes({
    commit
  }, roles) {

    return new Promise(resolve => {
      const accessedRouters = asyncRouterMap.filter(v => {
        // if (roles.indexOf('admin') >= 0) return true;
        if (hasPermission(roles, v)) {
          if (v.children && v.children.length > 0) {
            v.children = v.children.filter(child => {
              if (hasPermission(roles, child)) {
                return child
              }
              return false;
            });
            return v
          } else {
            return v
          }
        }
        return false;
      });
      commit('SET_ROUTES', accessedRouters)
      console.log(roles,accessedRouters);
      resolve(accessedRouters)
    })
  }
}


export default {
  namespaced: true,
  state,
  mutations,
  actions
}
